package cn.yh.register.oss.service.impl;

import cn.yh.register.common.exception.RegisterException;
import cn.yh.register.common.result.Result;
import cn.yh.register.common.result.ResultCodeEnum;
import cn.yh.register.oss.service.FileService;
import cn.yh.register.oss.util.ConstantOssPropertiesUtils;
import com.alibaba.excel.util.StringUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class FileServiceImpl implements FileService {
    /**
     * 上传文件到阿里云
     *
     * @param file 文件对象
     * @return 文件的网络地址
     */
    @Override
    public String upload(MultipartFile file) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ConstantOssPropertiesUtils.EDNPOINT,
                ConstantOssPropertiesUtils.ACCESS_KEY_ID, ConstantOssPropertiesUtils.SECRECT);
        // 获取原始文件名
        String filename = file.getOriginalFilename();
        if (!StringUtils.isEmpty(filename)) {
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            String ext = filename.substring(filename.lastIndexOf("."));
            filename = timeUrl + "/" + System.currentTimeMillis() + ext;
        }

        try {
            //上传的请求对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(ConstantOssPropertiesUtils.BUCKET, filename, file.getInputStream());
            //上传到存储空间
            ossClient.putObject(putObjectRequest);
            //返回文件的网络地址
            return "https://" + ConstantOssPropertiesUtils.BUCKET + "." + ConstantOssPropertiesUtils.EDNPOINT + "/" + filename;
        } catch (IOException e) {
            throw new RegisterException("文件上传失败！", ResultCodeEnum.FAIL.getCode());
        }
    }
}
